package com.shushan.home;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.home.bean.ExtractVipBean;
import com.shushan.home.bean.OpenExtractVipBean;
import com.shushan.login.bean.ChildBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.bean.WXPayBean;
import com.shushan.service.DialRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.shushanbao.wxapi.WXPayEntryActivity;
import com.shushan.util.SharedPreferencesUtils;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


/**
 * @ClassName: OpenExtractVipActivity
 * @Desciption: 提分vip开通
 * @author: yichaohua
 * @date: 2018-10-31
 */
public class OpenExtractVipActivity extends NavigationLoseActivity implements View.OnClickListener {

    private static final String TAG = "OpenExtractVipActivity";

    private RelativeLayout allLayout,chineseLayout,mathLayout,englishLayout;
    private TextView allTextView,chineseTextView,mathTextView,englishTextView;
    private TextView allCostTv;
    private TextView allFavorableTv;
    private TextView dataTv;
    private TextView chineseCostTv;
    private TextView chineseFavorableTv;
    private TextView mathCostTv;
    private TextView mathFavorableTv;
    private TextView englishCostTv;
    private TextView englishFavorableTv;
    private TextView payText;
    private TextView payActionText;
    private TextView wxCopyText;

    private OpenExtractVipBean selectVipBean;
    private OpenExtractVipBean allVipBean;
    private OpenExtractVipBean chineseVipBean;
    private OpenExtractVipBean mathVipBean;
    private OpenExtractVipBean englishVipBean;
    private BabyApplication babyApplication = BabyApplication.getInstance();
    private IWXAPI api;
    private ClipboardManager clipboardManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.open_extract_vip_activity);

        setTitle("提分计划");
        ChildBean currentChildBean = babyApplication.getCurrentChildBean();
        if(currentChildBean != null){
            setRightTitle(currentChildBean.gradeName + (currentChildBean.semester.equals("UP")?"上":"下"));
        }

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);

        initView();

        getData();
    }

    private void initView() {
        wxCopyText = findViewById(R.id.open_extract_wx_copy_tv);
        wxCopyText.setOnClickListener(this);
        payActionText = findViewById(R.id.extract_vip_pay_ation_tv);
        payActionText.setOnClickListener(this);
        payText = findViewById(R.id.extract_vip_pay_tv);
        allCostTv = findViewById(R.id.extract_vip_all_cost_tv);
        allFavorableTv = findViewById(R.id.extract_vip_all_favorable_tv);
        allFavorableTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        dataTv = findViewById(R.id.extract_vip_all_date_tv);
        chineseCostTv = findViewById(R.id.extract_vip_chinese_cost_tv);
        chineseFavorableTv = findViewById(R.id.extract_vip_chinese_favorable_tv);
        chineseFavorableTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        mathCostTv = findViewById(R.id.extract_vip_math_cost_tv);
        mathFavorableTv = findViewById(R.id.extract_vip_math_favorable_tv);
        mathFavorableTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        englishCostTv = findViewById(R.id.extract_vip_english_cost_tv);
        englishFavorableTv = findViewById(R.id.extract_vip_english_favorable_tv);
        englishFavorableTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        allTextView = findViewById(R.id.extract_vip_all_tv);
        chineseTextView = findViewById(R.id.extract_vip_chinese_tv);
        mathTextView = findViewById(R.id.extract_vip_math_tv);
        englishTextView = findViewById(R.id.extract_vip_english_tv);
        allLayout = findViewById(R.id.extract_vip_all_layout);
        allLayout.setOnClickListener(this);
        chineseLayout = findViewById(R.id.extract_vip_chinese_layout);
        chineseLayout.setOnClickListener(this);
        mathLayout = findViewById(R.id.extract_vip_math_layout);
        mathLayout.setOnClickListener(this);
        englishLayout = findViewById(R.id.extract_vip_english_layout);
        englishLayout.setOnClickListener(this);
    }

    private void getData() {
        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_EXTRACT_VIPS);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<ExtractVipBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(ExtractVipBean extractVipBean) {
                        if(extractVipBean != null){
                            allVipBean = extractVipBean.getALlVipBean();
                            selectVipBean = extractVipBean.getALlVipBean();
                            chineseVipBean = extractVipBean.getChineseVipBean();
                            mathVipBean = extractVipBean.getMathVipBean();
                            englishVipBean = extractVipBean.getEnglishVipBean();

                            if(allVipBean != null){
                                allTextView.setText(allVipBean.activity_name);
                                allCostTv.setText(allVipBean.cost_price + "");
                                allFavorableTv.setText("原价" + allVipBean.favorable_price);
                                dataTv.setText(allVipBean.end_time);
                            }

                            if(chineseVipBean != null){
                                chineseCostTv.setText(chineseVipBean.activity_name);
                                chineseCostTv.setText(chineseVipBean.cost_price + "");
                                chineseFavorableTv.setText("原价" + chineseVipBean.favorable_price);
                            }

                            if(mathVipBean != null){
                                mathCostTv.setText(mathVipBean.activity_name);
                                mathCostTv.setText(mathVipBean.cost_price + "");
                                mathFavorableTv.setText("原价" + mathVipBean.favorable_price);
                            }

                            if(englishVipBean != null){
                                englishCostTv.setText(englishVipBean.activity_name);
                                englishCostTv.setText(englishVipBean.cost_price + "");
                                englishFavorableTv.setText("原价" + englishVipBean.favorable_price);
                            }

                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.extract_vip_all_layout:
                selectVipType(1);
                break;
            case R.id.extract_vip_chinese_layout:
                selectVipType(2);
                break;
            case R.id.extract_vip_math_layout:
                selectVipType(3);
                break;
            case R.id.extract_vip_english_layout:
                selectVipType(4);
                break;
            case R.id.extract_vip_pay_ation_tv:
                orderPay();
                break;
            case R.id.open_extract_wx_copy_tv:
                if(clipboardManager == null) {
                    clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                }
                ClipData myClip = ClipData.newPlainText("wx_account1","shushan02");
                clipboardManager.setPrimaryClip(myClip);
                showToast("微信号复制成功");
                break;
            default:
                break;
        }
    }

    private void selectVipType(int type) {
        switch (type) {
            case 1:
                selectVipBean = allVipBean;
                allTextView.setBackgroundResource(R.drawable.extract_vip_brown_shape);
                chineseTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                mathTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                englishTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                break;
            case 2:
                selectVipBean = chineseVipBean;
                allTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                chineseTextView.setBackgroundResource(R.drawable.extract_vip_orange_shape);
                mathTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                englishTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                break;
            case 3:
                selectVipBean = mathVipBean;
                allTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                chineseTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                mathTextView.setBackgroundResource(R.drawable.extract_vip_green_shape);
                englishTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                break;
            case 4:
                selectVipBean = englishVipBean;
                allTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                chineseTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                mathTextView.setBackgroundResource(R.drawable.extract_vip_gray_shape);
                englishTextView.setBackgroundResource(R.drawable.extract_vip_violet_shape);
                break;
            default:
                break;
        }

        if(selectVipBean != null){
            payText.setText(selectVipBean.cost_price + "元");
        }
    }

    private void orderPay() {
        if(api.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            showToast("您未安装最新版本微信，不支持微信支付，请安装或升级微信版本");
            return;
        }

        if(selectVipBean == null){
            showToast("活动信息为空");
            return;
        }

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.PAY_ORDER);
        urlParse.putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("activity_vip_id",selectVipBean.id)
                .putValue("pay_type","app")
                .putValue("goods_name","提分计划活动优惠价￥" + selectVipBean.cost_price)
                .putValue("vip_time","365");

        if(BuildConfig.DEBUG){
            urlParse.putValue("money","0.01");
        }else {
            urlParse.putValue("money",selectVipBean.cost_price);
        }

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<WXPayBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(WXPayBean wxPayBean) {
                        if(wxPayBean != null){
                            PayReq req = new PayReq();
                            req.appId			= wxPayBean.appid;
                            req.partnerId		= wxPayBean.partnerid;
                            req.prepayId		= wxPayBean.prepayid;
                            req.nonceStr		= wxPayBean.noncestr;
                            req.timeStamp		= wxPayBean.timestamp + "";
                            req.packageValue	= wxPayBean.packageName;
                            req.sign			= wxPayBean.sign;
                            req.extData			= "app data"; // optional

                            Log.i(TAG,"out_trade_no=" + wxPayBean.out_trade_no);
                            SharedPreferencesUtils.setStringDate(Constants.OUT_TRADE_NO_SHAREPREFERS_KEY,wxPayBean.out_trade_no);
                            WXPayEntryActivity.type = 3;

                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
                            if(isChildControl){
                                setAllowBack(true);
                                Intent intent = new Intent(OpenExtractVipActivity.this,DialRTAService.class);
                                intent.putExtra("rtaType",4);
                                intent.putExtra("allowPackName",Constants.ALLOW_WECHAT_PACK_NAME);
                                startService(intent);
                            }

                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                        }else {
                            showToast("返回数据为空");
                        }

                        onBackAction();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }
}
